package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.SystemLog;
import cn.wolfcode.crm.mapper.SystemLogMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

public class SystemLogUtil {
    @Autowired
    SystemLogMapper systemLogMapper;

    public void writeLog(JoinPoint joinPoint){
        SystemLog systemLog = new SystemLog();
        //存入操作时间
        systemLog.setOpTime(new Date());
        //操作ip
        HttpServletRequest request = RequestUtil.getRequest();
        systemLog.setOpIp(request.getRemoteAddr());
        //操作用户
        Employee employee =(Employee) SecurityUtils.getSubject().getPrincipal();
        systemLog.setOpUser(employee);
        //执行参数
        Object[] args = joinPoint.getArgs();
        try {
            String s = new ObjectMapper().writeValueAsString(args);
            systemLog.setParams(s);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //执行的类名+方法
        String function = joinPoint.getTarget().getClass().getName() +":"
                + joinPoint.getSignature().getName();
        systemLog.setFunction(function);
        if (function.contains("query")){
            return;
        }
        systemLogMapper.insert(systemLog);
    }

}
